<template>
  <!-- sku详情 -->
  <div v-if="sku.length" id="detail" v-scroll-height class="w-43/100 p-4 border-1 rounded-lg border-gray-200 relative">
    <div class="font-bold text-xl">{{ spu.spuName }} {{ sku[skuIndex].skuDesc }}</div>
    <div class="m-3 flex justify-between items-center ">
      <div class="text-red-500 text-3xl font-bold "><span class="text-xl">￥</span>{{
        sku[skuIndex].skuPrice.toFixed(2) }}
      </div>
      <div>累计销量 {{ spu.totalSales }}</div>
    </div>
    <div class="flex py-3">
      <div class="w-1/10">送至</div>
      <div>{{ addressList.province }} {{ addressList.city }} {{ addressList.district }} {{
        addressList.detailAddress }}</div>
    </div>
    <div class="my-4 flex">
      <div class="w-1/10">规格选择</div>
      <div class="flex flex-wrap w-9/10 gap-2">
        <div v-for="(item, index) in sku" :key="index"
          class="flex items-center gap-1 bg-gray-100 p-1.5 rounded-sm cursor-pointer"
          :class="`${skuIndex == index ? 'border-1 bg-red-100 border-red-500 text-red-600' : ''}`"
          @click="$emit('changeSku', index)">
          <img :src='item.skuImages' alt="item.skuDesc" class="w-10">
          {{
            item.skuDesc
          }}
        </div>
      </div>
    </div>
    <div class="w-full absolute left-0 bottom-0 flex items-center justify-evenly py-5 border-t border-t-gray-200">
      <div class="w-10 h-10 bg-gray-200 flex justify-center items-center font-bold text-2xl  cursor-pointer"
        @click="quantity--">-
      </div>
      <div class="text-2xl">{{ quantity }}</div>
      <div class="w-10 h-10 bg-gray-200 flex justify-center items-center font-bold text-2xl  cursor-pointer"
        @click="quantity++">+
      </div>
      <div class="px-7 py-2 text-2xl bg-red-400 text-white font-bold rounded-sm cursor-pointer" @click="add">加入购物车</div>
      <div class="px-7 py-2 text-2xl bg-red-400 text-white font-bold rounded-sm  cursor-pointer">立即购买</div>
    </div>
  </div>

</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue';
import { getSKUAPI, getSpuByIdApi } from '@/apis/products';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAddressApi } from '@/apis/address';
import { addItemApi } from '@/apis/cart';
import { addOrderApi } from '@/apis/order';
const { skuIndex } = defineProps(['skuIndex'])
const route = useRoute()
const addressList = ref()
let quantity = ref(1)
// 自定义指令：处理滚动高度和位置
const scrollHeight = {
  mounted(el) {
    // 当前元素距离页面上方的尺寸
    let offsetTop = 0
    let elWidth = 0

    // 初始化
    const initProps = () => {
      offsetTop = el.offsetTop
      elWidth = el.offsetWidth / window.innerWidth
    }

    const updateElementStyle = () => {
      if (window.scrollY < offsetTop) {
        el.style.height = `${window.innerHeight - offsetTop + window.scrollY - 5}px`
        el.style.top = ''
        el.style.position = ''
        el.style.right = ''
        el.style.width = ''
      } else {
        let right = (window.innerWidth - (window.innerWidth * 0.75)) / 2

        el.style.position = 'fixed'
        el.style.right = `${right}px`
        el.style.top = '5px'
        el.style.width = `${elWidth * window.innerWidth}px`
        el.style.height = `${window.innerHeight - 10}px`
      }
    }
    const handleResize = () => {
      // initProps()
      updateElementStyle()
    }

    // 初始计算
    nextTick(() => {
      initProps()
      updateElementStyle()

      window.addEventListener('scroll', updateElementStyle)
      window.addEventListener('resize', handleResize)
    })

    // 清理
    el.__unmount = () => {
      window.removeEventListener('scroll', updateElementStyle)
      window.removeEventListener('resize', handleResize)
    }
  },
  unmounted(el) {
    el.__unmount?.()
  }
}
const getAddress = async () => {
  try {
    let res = await getAddressApi()
    addressList.value = res.data[0]
  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}
// 注册指令
const vScrollHeight = scrollHeight
const add = () => {
  try {
    let res = addItemApi({
      userId: localStorage.getItem('userId'),
      skuId: sku.value[skuIndex].skuId,
      quantity: quantity.value,
      isSelected: 1,
      skuAttr: sku.value[skuIndex].skuDesc,
      skuName: spu.value.spuName,
      skuPrice: sku.value[skuIndex].skuPrice,
    })
    ElMessage.success('添加成功')
  } catch (error) {
    ElMessage.error('添加失败')
  }
}
const spu = ref({})
const sku = ref([])
const getSpu = async () => {
  let res = await getSpuByIdApi(route.params.id)
  spu.value = res.data
}
const getSku = async () => {
  let res = await getSKUAPI(route.params.id)
  sku.value = res.data
}
const addOrder = async () => {
  try {
    await addOrderApi()
  } catch (error) {
    ElMessage.error('订单提交失败')
  }
}
getSpu()
getSku()
getAddress()
</script>

<style lang="scss" scoped></style>